package xc.utils;

import java.sql.*;
import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;


public class JdbcUtils {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://192.168.10.100:3306/bathingspot";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "Woaixuexi@1";
    private static final Integer INIT_POOL_SIZE = 10;
    private static final Integer MAX_POOL_SIZE = 20;
    private static final LinkedList<Connection> pool = new LinkedList<>();
    private static final ReentrantLock LOCK = new ReentrantLock();


    static {
        try {
            Class.forName(DRIVER);
            for (int i = 0; i < INIT_POOL_SIZE; i++) {
                pool.add(createConnection());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Connection createConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static Connection getConnection() throws SQLException {
        LOCK.lock();
        try {
            if (pool.isEmpty()) {
                if (pool.size() < MAX_POOL_SIZE) {
                    pool.add(createConnection());
                } else {
                    throw new SQLException("连接池已满！");
                }
            }
            return pool.removeFirst();
        } finally {
            LOCK.unlock();
        }
    }

    public static void returnConnection(Connection connection) {
        LOCK.lock();
        try {
            if (connection != null) {
                pool.addLast(connection);
            }
        } finally {
            LOCK.unlock();
        }
    }

    public static void closeConnection() {
        LOCK.lock();
        try {
            for (Connection connection : pool) {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            pool.clear();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            LOCK.unlock();
        }
    }

    public static void closeResource(ResultSet rs, PreparedStatement ps) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}